package cn.hzking.gjmall.net.loading.loadingview;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AppCompatDialog;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;

import com.wang.avi.AVLoadingIndicatorView;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

import cn.hzking.gjmall.R;
import cn.hzking.gjmall.utils.ScreenTool;

/**
 * Created by Administrator on 2018/2/5.
 */

public class GjLoadingUtils {
    private static final int LOADER_SIZE_SCALE = 12;
    private static final int LOADER_OFFSET_SCALE = 10;

    private static final CopyOnWriteArrayList<AppCompatDialog> LOADERS = new CopyOnWriteArrayList<>();


    private static final String DEFAULT_LOADER = LoaderStyle.LineSpinFadeLoaderIndicator.name();

    public static void showLoading(Context context, Enum<LoaderStyle> type) {
        showLoading(context, type.name(),true);
    }

    public static void showLoading(Context context, String type,boolean isCancel) {

        final AppCompatDialog dialog = new AppCompatDialog(context, R.style.dialog);

        final AVLoadingIndicatorView avLoadingIndicatorView = LoaderCreator.create(type, context);
        avLoadingIndicatorView.setIndicatorColor(Color.parseColor("#978365"));
        dialog.setContentView(avLoadingIndicatorView);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setCancelable(isCancel);
        int deviceWidth = ScreenTool.getScreenWidth(context);
        int deviceHeight = ScreenTool.getScreenHeight(context);

        final Window dialogWindow = dialog.getWindow();

        if (dialogWindow != null) {
            final WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = deviceWidth / LOADER_SIZE_SCALE;
            lp.height = deviceHeight / LOADER_SIZE_SCALE;
           // lp.height = lp.height + deviceHeight / LOADER_OFFSET_SCALE;
            lp.gravity = Gravity.CENTER;
        }
        LOADERS.add(dialog);
        dialog.show();
    }

    public static void showLoading(Context context,boolean isCancel) {
        showLoading(context, DEFAULT_LOADER,isCancel);
    }

    public static void stopLoading() {
        Iterator<AppCompatDialog> iterator = LOADERS.iterator();
        while (iterator.hasNext()){
            AppCompatDialog dialog = iterator.next();
            if (dialog != null) {
                if (dialog.isShowing()) {
                    dialog.cancel();
                }
                LOADERS.remove(dialog);
            }
        }
    }
}
